#!/usr/bin/python

from globals import log,app
import globals
import bluetooth
import threading

#/* ============================================================================= */
#/* FUNCTIONS: IMPLEMENTATIONS */
#/* ============================================================================= */

class BluetoothServer ( threading.Thread ):
  port = None
  queue = None
  
  def __init__(self, port, queue):
    self.port = port
    self.queue = queue
    threading.Thread.__init__ ( self )
    
  def run(self):
    log("[BluetoothServer] Initializing Bluetooth Server")
    
    server_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    server_sock.bind(("",self.port))
    server_sock.listen(5)
    
    while True: # main accept() loop

      if app.verbose:
        log("[BluetoothServer] Waiting for bluetooth conections...")

      client_sock,address = server_sock.accept()
      if address == None:
        if app.verbose:
          log("[BluetoothServer] Skipping null connection...")
        continue

      if app.verbose:
        log("[BluetoothServer] Accepted connection from "+str(address))
        
      t = BluetoothClientHandle(client_sock, self.queue)
      t.start()

    server_sock.close()
    
    if app.verbose:
      log("[BluetoothServer] Bye bye.")
    
    return True


class BluetoothClientHandle( threading.Thread ):
  def __init__(self, socket, queue):
    self.socket = socket
    self.queue = queue
    threading.Thread.__init__ ( self )
    
  def run ( self ):
    
    if app.verbose:
      log("[BluetoothClientHandle] Taking connection")
    while True:
      if app.verbose:
        log("[BluetoothClientHandle] waiting data...")
        
      buff = self.socket.recv(globals.MAX_MSG_SIZE)
      if not buff: break

      if app.verbose:
        log("[BluetoothClientHandle] got: "+buff)
      self.queue.addCommand(buff);
      #lircde_process_command
    
    if app.verbose:
      log("[BluetoothClientHandle] Connection finished")
      
    self.socket.close()
